$NG.AllReady(function (
    page,
    { useAction, useValuesChange, useUpdateRows, useUpdateRow, useDataIndexChange, useClick }
) {
    const mstform = $NG.getCmpApi("p_form_employ_salary")
    const dgrid1 = $NG.getCmpApi("p_form_employ_salary_d")

    const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_employ_salary_d");
    toolbar_dgrid.insert({
        id: "template_download",
        text: "模板下载",
        iconCls: "icon-InsertRow"
    });
    useClick(async function ({ args }) {
        const url = "http://nginx.clouddev.hisense.com/report/index.html#/tableDesign/TableManager/preview?rep_id=8570000000000015&multiCooperate=0&busCode=null&menucode=d50357aa-3f40-0577-cebd-6eeaef9c512b";
        // 打开报表并传递参数
        $NG.open(url, { AppTitle: "用工工资导入模板" });
    }, "template_download");
    if (page.oType == 'add') {
        setName()
        getGzzc()
    }
    function setName() {
        $NG.updateState((updater) => {
            updater.data.p_form_employ_salary.setProps({
                bill_name: `${mstform.getItem("phid_pc").getText() || ""}-${mstform.getItem("phid_cycle").getText() || ""}外包工资表`
            })
        })
    }
    useDataIndexChange(({ args, instance }) => {
        getName()
        const row = args[0];
        if (args[0].u_name) {
            $NG.execServer(
                "getWbInfo2",
                { phid: `${args[0].u_name}` },
                function (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    console.log(datas, "获取值datas");
                    let ygType = ''
                    if (datas.yglx == '实施外包用工') {
                        ygType = '01'
                    }else if(datas.yglx == '研发二次开发用工'){
                        ygType = '02'
                    }else{
                        ygType = '03'
                    }
                    row.idno = datas.sfz;
                    row.u_employment_type = ygType
                    dgrid1.updateRow(row);
                    dgrid1.refreshView();
                }
            );
        }
        
    }, 'p_form_employ_salary_d.u_name');
    getName()
    function getName() {
        $NG.updateUI((updater) => {
            const fields = ["u_name"];
            fields.forEach((field) => {
                // $NG.getPageUI();
                // 根据组件目录设置路径，可能存在
                // fieldSetForm
                // PCFieldSetPanelGroup[i][field]
                updater.editGrid.p_form_employ_salary_d[field].setProps({
                    // hidden: true, //隐藏
                    // required: true, //必输
                    // disabled: true, //只读
                    onBeforeOpen: async () => {
                        var phid_pc = mstform.getItem('phid_pc').getValue();
                        var u_cnt_name = mstform.getItem('u_cnt_name').getValue();
                        if (!phid_pc || !u_cnt_name) {
                            $NG.alert("请先选择项目以及合同");
                            return false;
                        } else {
                            return true;
                        }
                    },
                    clientSqlFilter: `xm = '${mstform.getItem('phid_pc').getValue()}' and htphid = '${mstform.getItem('u_cnt_name').getValue()}' and  ( ry_zt = '32' 
                    OR ( 
                      ry_zt = '35' 
                      AND real_enddt >= TRUNC(SYSDATE, 'MM') 
                      AND real_enddt < ADD_MONTHS(TRUNC(SYSDATE, 'MM'), 1)
                    )
                  ) `, //过滤条件
                    // placeholder: "请选择", //输入框字段加提示语
                    // data: [{ value: "01", label: "实施外包用工" }], //下拉过滤
                });
            });
        });

    }
    function initUserType(_data) {       
        $NG.execServer(
            "searchJfdw",
            { phid: `'${mstform.getItem("u_cnt_name").getValue()}'` },
            function (res) {
                if(res.count ==0) return
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`甲方：`, datas);
                //帮助字段赋值
                _data.forEach((item) => {
                    item.u_cz_org = datas.jfdw,
                    item.u_cz_org_EXName = datas.jfmc
                  })
                  dgrid1.refreshView()
            }
        );

      }
    function getGzzc() {
        $NG.execServer("getInDate", {}, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_employ_salary.setProps({
                    phid_cycle: {
                        label: _data.bill_name,
                        value: _data.phid
                    }
                })
            })
        })
    }
    // 项目监听
    useValuesChange(({ args }) => {
        getProjectInfo()
        cntMFilter()
        setName()
        getName()
    }, "p_form_employ_salary.phid_pc")
    useValuesChange(({ args }) => {
        setName()
    }, "p_form_employ_salary.phid_cycle")
    // 合同监听

    useValuesChange(({ args }) => {
        console.log(`合同监听`, args);
        getCntInfo()
        getName()
    }, "p_form_employ_salary.u_cnt_name")
    // 表格编辑监听
    useUpdateRow(({ args }) => {
        autoInNameToPhid(args[0])
        getCntJfInfo(args[0])
        args[0].u_total_tax = (Number(args[0].u_total) * 1.0672 + Number(args[0].u_manage_amt)) || 0
        dgrid1.refreshView()
    }, "p_form_employ_salary_d")

    // 表格行为监听
    useUpdateRows(({ args }) => {
        initUserType(args[0])
        caculatedgrid();
        sum()
    }, "p_form_employ_salary_d")

    // 根据项目带编码：表格
    function autoInNameToPhid(item) {
        // 查询相应项目的信息
        getProjectInfo(true, item.u_pc_name, (_data) => {
            if (_data) {
                item.u_pc_no = _data.phid_pc
                item.u_pc_no_EXName = _data.pc_no
            }
            dgrid1.refreshView()
        })
    }
    function caculatedgrid() {
        console.log(`监听生效`);
        let u_total_dgrid1 = 0;
        let u_total_dgrid2 = 0;
        let u_total_dgrid = 0; //合计总费用

        dgrid1.getRows().forEach((items, rowIndex) => {
            // 人工费合计=人员费率*数量*人月
            items.u_total = (Number(items.u_real_salary) || 0) + (Number(items.u_tax) || 0) + (Number(items.u_social_security_self) || 0)+ (Number(items.u_social_security_comp) || 0);
            items.u_total_tax = items.u_total*1.0672 + (Number(items.u_manage_amt) || 0)
            dgrid1.refreshView();
        });

    }
    // 汇总含税金额
    function sum() {
        const _row = dgrid1.getRows()
        let _count = 0;
        _row.forEach(element => {
            _count += (Number(element.u_total) * 1.0672 + Number(element.u_manage_amt)) || 0
        });
        $NG.updateState((updater) => {
            updater.data.p_form_employ_salary.setProps({
                u_total_amt: _count,
                u_sy_amt: _count
            })
        })
    }
    getProjectInfo()
    // 获取项目
    function getProjectInfo(isReturn = false, phid = mstform.getItem("phid_pc").getValue(), fun) {
        try {
            setTimeout(() => {
                $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
                    if (!res.data) return
                    const _data = JSON.parse(res.data)[0].extendObjects
                    console.log(`获取项目信息`, _data);
                    if (isReturn) {
                        fun(_data)
                    } else {
                        $NG.updateState((updater) => {
                            updater.data.p_form_employ_salary.setProps({
                                u_pc_no: _data.pc_no, //项目编码
                                u_devision: {
                                    //事业部or组织
                                    value: _data.org_phid,
                                    label: _data.org_name,
                                },
                                phid_emp: {
                                    label: _data.project_manager_name,
                                    value: _data.project_manager_phid
                                },
                                u_sqgw: {
                                    //售前顾问
                                    value: _data.user_sqgw_phid,
                                    label: _data.user_sqgw_name,
                                },
                                u_regional_center: {
                                    //区域中心
                                    value: _data.regional_center_phid,
                                    label: _data.regional_center_name,
                                },
                                u_product_line: {
                                    //产品线
                                    value: _data.midwife_phid,
                                    label: _data.midwife_name,
                                },
                                u_dept: {
                                    //部门
                                    value: _data.dept_phid,
                                    label: _data.dept_name,
                                },
                                u_pc_type: {//项目类型
                                    value: _data.type_phid,
                                    label: _data.type_name,
                                },
                            })
                        })
                    }
                })
            }, 100)
        } catch (err) {
            $NG.alert("获取项目信息发生失败请检查~")
        }
    }

    //合同根据项目ID过滤
    cntMFilter()
    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            console.log('过滤参数检查', updater);
            updater.fieldSetForm.p_form_employ_salary.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi('p_form_employ_salary').getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi('p_form_employ_salary').getItem('phid_pc').getValue() && {
                    clientSqlFilter: {
                        xm_no: $NG.getCmpApi('p_form_employ_salary').getItem('phid_pc').getValue()
                    }
                }),
            });
        });
    }
    // 获取合同信息
    function getCntInfo() {
        $NG.execServer(
            "GetWbhtInfo",
            { phid: mstform.getItem("u_cnt_name").getValue() },
            function (res) {
                console.log(res);
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`合同：`, datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_employ_salary.setProps({
                        u_cnt_no: datas.bill_no,
                        u_yg_htlx:datas.htlx,
                        phid_supply_ent: {
                            label: datas.wbgs_name,
                            value: datas.wbgs
                        }
                    });
                });
            }
        );
    }
});

